/* eslint no-param-reassign: "off" */

import { FElement, Config } from './types';
import { getCache, setCache } from './cache';
import { jsonToData } from './json-data';
import { getAttrVal, mergeObj } from './tools';


export function getMCData(dom: Element, clickConfig: Config): any {
  const node: FElement = dom as FElement;
  const attrName = clickConfig.clickAttr as string;
  const key = getAttrVal(node, attrName);
  if (key) {
    let mcData: any = getCache(key);
    if (!mcData) {
      mcData = jsonToData(key);
      if (mcData) {
        const { clickData, clickCount, clickType } = clickConfig;
        if (clickData) {
          mcData.valLab = mergeObj(clickData.valLab, mcData.valLab);
          mcData.options = mergeObj(clickData.options, mcData.options);
        }
        mcData.config = { clickCount, clickType, count: 0, ...mcData.config };
      }
      setCache(key, mcData);
    }
    return mcData;
  }
}

export function getMVData(dom: Element, viewConfig: Config): any {
  const node: FElement = dom as FElement;
  const attrName = viewConfig.viewAttr as string;
  let mvData = node[attrName];
  if (!mvData) {
    const key = getAttrVal(node, attrName);
    if (key) {
      mvData = getCache(key);
      if (!mvData) {
        mvData = jsonToData(key);
        const { viewData, viewCount, viewDuration } = viewConfig;
        if (viewData) {
          mvData.valLab = mergeObj(viewData.valLab, mvData.valLab);
          mvData.options = mergeObj(viewData.options, mvData.options);
        }
        mvData.config = { viewCount, viewDuration, count: 0, ...mvData.config };
        setCache(key, mvData);
        node[attrName] = mvData;
      } else {
        node[attrName] = mvData;
      }
    }
  }
  return mvData;
}

export default { getMCData, getMVData };
